﻿using Android.App;
using Android.Widget;
using Android.OS;
using Express.Tools;
using System.Linq;
using Express.Core.Controls;
using Express.Core.Requests;
using ZXing.Mobile;

namespace Express.App
{
    [Activity(Label = "@string/ApplicationName", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private EditText txtId;
        private Button btnQuery;
        private ListView detailList;
        private Button btnScan;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            txtId = FindViewById<EditText>(Resource.Id.txtExpressId);
            detailList = FindViewById<ListView>(Resource.Id.detailList);
            btnQuery = FindViewById<Button>(Resource.Id.btnQuery);
            btnScan = FindViewById<Button>(Resource.Id.btnScan);
            btnScan.Click += BtnScan_Click;
            btnQuery.Click += BtnQuery_Click;
        }

        private async void BtnScan_Click(object sender, System.EventArgs e)
        {
            MobileBarcodeScanner.Initialize(Application);
            var scanner = new ZXing.Mobile.MobileBarcodeScanner();

            var result = await scanner.Scan();

            if (result != null)
                txtId.Text = result.Text;
        }

        private async void BtnQuery_Click(object sender, System.EventArgs e)
        {
            try
            {
                string expId = this.txtId.Text;
                if (string.IsNullOrEmpty(expId))
                {
                    Toast.MakeText(this, "请输入快递单号", ToastLength.Long).Show();
                    return;
                }
                this.btnQuery.Enabled = false;
                KDNiaoHelper helper = new KDNiaoHelper();
                //识别订单
                var ret = await helper.OrderTracesSubByJson(expId);
                if (ret != null && ret.Shippers.Count > 0)
                {
                    var exTypeInfo = ret.Shippers.FirstOrDefault();
                    var orderTrace = await helper.GetOrderTracesByJson(exTypeInfo.ShipperCode, ret.LogisticCode);
                    if (orderTrace.Success && orderTrace.Traces != null)
                    {
                        detailList.Adapter = new ItemListAdapter(this, orderTrace.Traces.OrderByDescending(i => i.AcceptTime).ToList());
                    }
                }
                else
                {
                    Toast.MakeText(this, "无此快递单号", ToastLength.Long).Show();
                }
                this.btnQuery.Enabled = true;
            }
            catch (System.Exception ex)
            {
                Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
            }
        }
    }
}

